package cn.time1024.time_app.ui.notifications

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import cn.time1024.time_app.databinding.FragmentNotificationDetailBinding
import com.example.timeassistant.network.ApiService
import com.example.timeassistant.network.ResponseEnvelope
import com.example.timeassistant.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class NotificationDetailFragment : Fragment() {

    private var _binding: FragmentNotificationDetailBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = FragmentNotificationDetailBinding.inflate(inflater, container, false)
        val id = arguments?.getLong("notificationId") ?: 0L
        loadDetail(id)
        return binding.root
    }

    override fun onDestroyView() { super.onDestroyView(); _binding = null }

    private fun loadDetail(id: Long) {
        RetrofitClient.api.getNotificationDetail(notificationId = id)
            .enqueue(object: Callback<ResponseEnvelope<ApiService.NotificationItem>> {
                override fun onResponse(
                    call: Call<ResponseEnvelope<ApiService.NotificationItem>>,
                    response: Response<ResponseEnvelope<ApiService.NotificationItem>>
                ) {
                    val item = response.body()?.data
                    binding.tvTitle.text = item?.title ?: "(无标题)"
                    val type = item?.type ?: "未知"
                    val source = item?.sourceUrl ?: ""
                    binding.tvMeta.text = "$type"
                    binding.tvContent.text = when(type) {
                        "daily_ai_news" -> {
                            val details = item?.details
                            if (!details.isNullOrBlank()) renderDailyDetails(details) else (item?.aiContent ?: item?.content ?: "")
                        }
                        else -> item?.content ?: ""
                    }
                    binding.tvSource.text = source
                }
                override fun onFailure(call: Call<ResponseEnvelope<ApiService.NotificationItem>>, t: Throwable) {}
            })
    }

    /**
     * 将后端保存的每日明细 JSON 渲染为可阅读的文本内容
     * 格式：显示 date 作为标题行；逐条显示 title、desc、source 与 url
     */
    private fun renderDailyDetails(detailsJson: String): String {
        return try {
            val root = org.json.JSONObject(detailsJson)
            val date = root.optString("date")
            val arr = root.optJSONArray("items")
            val sb = StringBuilder()
            if (!date.isNullOrBlank()) { sb.append(date).append('\n').append('\n') }
            if (arr != null) {
                for (i in 0 until arr.length()) {
                    val obj = arr.optJSONObject(i) ?: continue
                    val title = obj.optString("title")
                    val desc = obj.optString("desc")
                    val source = obj.optString("source")
                    val url = obj.optString("url")
                    if (title.isNotBlank()) sb.append("• ").append(title).append('\n')
                    if (desc.isNotBlank()) sb.append(desc).append('\n')
                    if (source.isNotBlank()) sb.append("来源：").append(source).append('\n')
                    if (url.isNotBlank()) sb.append("链接：").append(url).append('\n')
                    sb.append('\n')
                }
            }
            sb.toString().trim()
        } catch (_: Throwable) {
            detailsJson
        }
    }
}